<template>
    <div class="content">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>审批任务列表</span>
        </div>
        <div class="content-table">
          <div class="table-main">
            <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :height="tableMaxHeight" highlight-current-row ref="approvalTable" @expand-change="handleExpandChange" class="content-table-item">
              <el-table-column type="expand">
                <template slot-scope="{row,$index}">
                  <el-table v-loading="expandTableLoading" :data="expandTableData" style="width: 100%">
                    <el-table-column prop="materialName" label="物料名称" align="center" width="180"></el-table-column>
                    <el-table-column prop="materialCode" label="物料编码" align="center" width="180"></el-table-column>
                    <el-table-column prop="materialComp" label="物料单位" align="center" width="80"></el-table-column>
                    <el-table-column prop="materialStandard" label="物料规格" align="center" width="120"></el-table-column>
                    <el-table-column prop="approvalNum" label="申请数量" align="center" width="100"></el-table-column>
                    <el-table-column prop="purchaseDate" label="要货日期" align="center" width="150"></el-table-column>
                    <el-table-column prop="customerName" label="客户名称" align="center" width=""></el-table-column>
                    <el-table-column prop="materialRemarks" label="行备注" align="center" width=""></el-table-column>
                  </el-table>
                </template>
              </el-table-column>
              <el-table-column type="index" label="序号" align="center" width=""></el-table-column>
              <el-table-column prop="purchaseRequestCode" label="采购需求单号" align="center" width="150"></el-table-column>
              <el-table-column prop="stepNumber" label="审批步骤" align="center" width=""></el-table-column>
              <el-table-column prop="userName" label="审批人" align="center" width="150"></el-table-column>
              <el-table-column prop="result" label="审批状态" align="center" width="">
                <template slot-scope="{ row, $index }">
                  <el-tag effect="dark" size="small" type="info" v-if="row.result == 0">待审批</el-tag>
                  <el-tag effect="dark" size="small" type="success" v-if="row.result == 1">审批通过</el-tag>
                  <el-tag effect="dark" size="small" type="danger" v-if="row.result == 2">驳回</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="comments" label="审批备注" align="center" width="180"></el-table-column>
              <el-table-column prop="approvalTime" label="审批时间" align="center" width="150"></el-table-column>
              <el-table-column prop="createdBy" label="创建人" align="center" width=""></el-table-column>
              <el-table-column prop="createdDate" label="创建时间" align="center" width="150"></el-table-column>
              <el-table-column prop="" label="操作" align="center" width="150">
                <template slot-scope="{ row, $index }">
                  <el-button v-show="false" type="text" size="mini" @click="examineOrEditEvent(row,'detail')">详情</el-button>
                  <el-button v-show="false" type="text" size="mini" @click="examineOrEditEvent(row,'edit')">编辑</el-button>
                  <el-button type="text" size="mini" @click="approvalEvent(row)" :disabled="!((row.result == 0 || row.result == 2) && userInfo.isApproval)">审批</el-button>
                  <el-button type="text" size="mini" @click="requestApprovalEvent(row)" :disabled="!(row.result == 2 && !userInfo.isApproval)">申请审批</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <div class="content-footer">
          <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[20,40,80,100,200]" :page-size="pageSize" background :layout="paginationLayout" :total="total"></el-pagination>
        </div>
      </el-card>
      <!-- 审批dialog -->
      <el-dialog title="审批详情" :visible.sync="dialogInfo.dialogVisible" :width="approvalWidth" :close-on-click-modal="false" :destroy-on-close="true" @close="approvalDialogClose">
        <el-form ref="form" :model="dialogInfo" label-width="80px">
          <el-form-item label="审批状态">
            <el-radio-group v-model="dialogInfo.approvalStatus">
              <el-radio label="同意"></el-radio>
              <el-radio label="驳回"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="审批意见">
            <el-input type="textarea" v-model="dialogInfo.approvalDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="approvalConfirmEvent">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  import { reqApprovalTaskList,reqApprovalTask, reqReApprovalTask, reqMaterialInfoByCode } from "@/api/approvalTask.js";
  import { startProgramWitApplicationId } from "@/utils/jingzhi.js";
  import T from "@/utils/tools.js";
  import M from "moment";
  import { Dialog } from "vant";
  export default {
    name:"ApprovalTask",  //采购需求任务列表
    data() {
      return {
        userInfo:{
          username:"",
          nickname:"",
          isApproval:true
        },
        tableData:[],
        currentPage:1,
        pageSize:20,
        total:0,
        tableLoading:false,
        dialogInfo:{
          dialogVisible:false,
          approvalStatus:"",
          approvalDesc:"",
          currentSelected:null
        },
        tableMaxHeight:450,
        clientWidth:1920,  //设备屏幕宽度
        expandTableData:[],
        expandTableLoading:false
      }
    },
    mounted(){
      this.getUserInfo();
      this.getApprovalTaskList();
      //精致环境下进行自动旋转
      const isDevelopment = process.env.NODE_ENV === 'development';
      if(!isDevelopment){
        autoOrientation();
      }
      this.calculateTableMaxHeight();
      window.addEventListener("resize",this.calculateTableMaxHeight);
      document.title = "采购审批任务列表";
    },
    beforeDestroy(){
      window.removeEventListener("resize",this.calculateTableMaxHeight);
    },
    computed:{
      paginationLayout(){
        const domWidth = this.clientWidth;
        if(domWidth >= 300 && domWidth <= 600){
          return "prev, pager, next,total";
        }
        if(domWidth > 600){
          return "prev, pager, next,total, sizes, jumper";
        }
      },
      approvalWidth(){
        const domWidth = this.clientWidth;
        if(domWidth >= 300 && domWidth <= 600){
          return "90%";
        }
        if(domWidth > 600){
          return "40%";
        }
      }
    },
    methods:{
      //获取审批任务列表
      getApprovalTaskList(){
        const currentPage = this.currentPage;
        const pageSize = this.pageSize;
        const username = this.userInfo.username;
        const parameter = { page:currentPage, size:pageSize, userName:username };
        if(!parameter.userName){
          parameter.userName = T.getUserInfoByToken().preferred_username;
        }
        reqApprovalTaskList(parameter).then(response => {
          if(response.data.code === 200){
            const list = this.dealResponseData(response.data.data.content);
            const total = response.data.data.totalElements;
            this.tableData = list;
            this.total = total;
          }
          console.log("分页获取审批任务列表api",response);
        }, error => {
          console.log("分页获取审批任务列表api",error);
        })
      },
      examineOrEditEvent(row,type = 'detail'){
        const { purchaseRequestCode,purchaseRequestId } = row;
        this.$confirm(`即将打开新的标签页, 是否继续?`, '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'}).then(async confirm => {
          const jumpResult = await this.jumpPurchaseDemand(purchaseRequestId,type);
          if(!jumpResult){
            this.$notify({title:"提示", message:"标签页打开失败，请重试",type:"warning",duration:2000});
          }
        })
      },
      approvalEvent(row){
        this.dialogInfo.currentSelected = row;
        this.dialogInfo.dialogVisible = true;
      },
      requestApprovalEvent(row){
        const { purchaseRequestCode,purchaseRequestId,userName } = row;
        const { username,nickname } = this.userInfo;
        const parameter = {
          userName:userName,
          purchaseRequestCode
        }
        Dialog.confirm({title:'提示',message:`再次对单号${purchaseRequestCode}申请审批, 是否继续?`}).then(confirm => {
          reqReApprovalTask(parameter).then(response => {
            if(response.data.code === 200){
              this.$notify({title:"提示", message:"已提交申请",type:"success",duration:2000});
              this.getApprovalTaskList();
            }
            console.log("再次申请审批接口api",response);
          }, error => {
            this.$notify({title:"提示", message:"提交申请失败,请重试",type:"error",duration:2000});
            console.log("再次申请审批接口api",response);
          })
        })  
      },
      approvalConfirmEvent(){
        if(this.dialogInfo.approvalStatus == ""){
          this.$notify({title:"提示", message:"请选择审批状态",type:"error",duration:2000});
          return;
        }
        const info = this.dialogInfo.currentSelected;
        const { approvalStatus, approvalDesc } = this.dialogInfo;
        const d = M().format("YYYY-MM-DD HH:mm:ss");
        const state = approvalStatus == '同意' ? 1 : approvalStatus == '驳回' ? 2 : 0;
        const parameter = {id:info.id,userId:info.userId,userName:info.userName,stepId:info.stepId,stepNumber:info.stepNumber,approvalTime:d,result:state,comments:approvalDesc};
        console.log(parameter);
        reqApprovalTask(parameter).then(response => {
          if(response.data.code == 200){
            this.$notify({title:"提示", message:"审批成功",type:"success",duration:2000});
            this.getApprovalTaskList();
            this.dialogInfo.dialogVisible = false;
          }
          console.log("审批更新api",response);
        }, error => {
          this.$notify({title:"提示", message:"审批失败，请重试",type:"error",duration:2000});
          console.log("审批更新api",error);
        })
      },
      handleCurrentChange(val){
        this.currentPage = val;
      },
      handleSizeChange(val){
        this.pageSize = val;
      },
      //跳转采购需求页
      async jumpPurchaseDemand(id,type){
        const purchaseDemandId = id || 27;
        const path0 = "/detail/" + purchaseDemandId + "/detail";
        const path1 = "/edit/" + purchaseDemandId;
        const path = type === "detail" ? path0 : path1;
        const applicationId = 'new.yk.genieos.ams.scc.procurement-management.purchasing-demand';
        const jumpResult = await startProgramWitApplicationId(applicationId,path);
        console.log('调用精致跳转api====>',jumpResult);
        return jumpResult;
      },
      dealResponseData(list){
        const array = new Array();
        const responseList = list;
        if(responseList.length > 0 && responseList[0].klApprovalTaskList){
          //创建人数据
          this.userInfo.isApproval = false;
          for(let k = 0; k < responseList.length; k++){
            const l = responseList[k].klApprovalTaskList;
            //采购需求单号 审批步骤 审批人 审批状态 审批备注 审批时间 创建人 创建时间
            for(let m = 0 ; m < l.length; m ++){
              const r = l[m];
              r.createdBy = responseList[k].createdBy;
              r.expand = false;
              array.push(r);
            }
          }
        } else {
          //审批人数据
          this.userInfo.isApproval = true;
          for(let h = 0; h < responseList.length; h ++){
            const g = responseList[h];
            g.expand = false;
            array.push(g);
          }
        }
        console.log("对响应审批列表数据处理结果===>",array);
        return array;
      },
      handleExpandChange(row,expanded){
        const list = this.tableData;
        for(let j = 0; j < list.length; j ++){
          if(list[j].expand){
            this.$refs.approvalTable.toggleRowExpansion(list[j],false);
          }
        }
        row.expand = !row.expand;
        this.$refs.approvalTable.toggleRowExpansion(row,row.expand);
        this.getMaterialInfoByPurchaseRequestCode(row.purchaseRequestCode);
        this.expandTableData = [];
      },
      //根据采购需求编号获取物料明细
      getMaterialInfoByPurchaseRequestCode(code){
        this.expandTableLoading = true;
        reqMaterialInfoByCode(code).then(response => {
          if(response.data.code === 200){
            const list = response.data.data;
            const tmp = list.map(val => {
              return {
                materialCode:val.materialFields.code,
                materialName:val.materialFields.name,
                materialComp:val.materialFields.comp,
                materialStandard:val.materialFields.standard,
                approvalNum:val.num,
                materialRemarks:val.materialRemarks,
                purchaseDate:val.purchaseDate,
                customerName:val.customerName
              }
            })
            this.expandTableData = tmp;
          }
          console.log("根据采购需求号获取物料信息",response);
          this.expandTableLoading = false;
        }, error => {
          console.log("根据采购需求号获取物料信息",error);
          this.expandTableLoading = false;
        })
      },
      approvalDialogClose(){
        this.dialogInfo.approvalStatus = "";
        this.dialogInfo.approvalDesc = "";
      },
      calculateTableMaxHeight(){
        const height = document.documentElement.scrollHeight;
        const domWidth = document.documentElement.clientWidth;
        this.clientWidth = domWidth;
        console.log("当前屏幕宽度:",domWidth);
        this.$nextTick(() => {
          if(domWidth >= 300 && domWidth <= 600){
            this.tableMaxHeight = height - 140;
          } else {
            this.tableMaxHeight = height - 160;
          }
        });
      },
      //获取用户信息
      getUserInfo(){
        const info = T.getUserInfoByToken();
        this.userInfo.username = info.preferred_username;  //liwen dx1003
        this.userInfo.nickname = info.given_name;  //李雯
        console.log('解析token获取到的用户信息===>',info);
      }
    }
  }
  </script>
  
<style lang='scss' scoped>
.content{
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1%;
  box-sizing: border-box;

  .content-footer{
    display: flex;
    justify-content: flex-end;
    .el-pagination{
      white-space: normal !important;
    }
  }
}
/*
::v-deep .el-table__header th {
  padding: 0;
}
::v-deep .el-table__row {
  margin-bottom: 15px;
}
::v-deep .el-table .el-table__cell{
  padding: 0;
}
*/
</style>